import { createRouter, createWebHashHistory } from 'vue-router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { ElMessage } from 'element-plus'
import { localCache } from '@/utils/cache'
import { LOGIN_TOKEN } from '@/global/constant'
import { useTitle } from '@vueuse/core'
import useLoginStore from '@/store/login'
import { mapMenusToRoutes } from '@/utils/map-menus'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/main'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        title: '登陆页'
      }
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/index.vue'),
      meta: {
        title: '首页'
      }
      /* children: [
        {
          path: '/main/analysis/overview',
          component: () => import('@/views/main/analysis/overview/index.vue'),
          meta: {
            title: '核心技术'
          }
        },
        {
          path: '/main/analysis/dashboard',
          component: () => import('@/views/main/analysis/dashboard/index.vue'),
          meta: {
            title: '商品统计'
          }
        },
        {
          path: '/main/system/user',
          component: () => import('@/views/main/system/user/index.vue'),
          meta: {
            title: '用户管理'
          }
        },
        {
          path: '/main/system/role',
          component: () => import('@/views/main/system/role/index.vue'),
          meta: {
            title: '角色管理'
          }
        }
      ] */
    },
    {
      path: '/404',
      name: 'notFound',
      component: () => import('@/views/not-found/index.vue'),
      meta: {
        title: '404页面'
      }
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404', // 直接写路径
      name: 'Any'
    }
  ]
})

// 导航守卫 beforEach
router.beforeEach((to, _from, next) => {
  nprogress.start()

  useTitle(`宏源商场后台管理` + to.meta.title)
  const token = localCache.getCache(LOGIN_TOKEN)

  if (token) {
    if (to.path.startsWith('/login')) {
      ElMessage.warning('请勿重复登陆')
      next('/main')
    } else if (to.path === '/main') {
      const loginStore = useLoginStore()
      const { firstMenu } = mapMenusToRoutes(loginStore.userMenus as any[])
      next(firstMenu.url)
    } else {
      next()
    }
  } else {
    if (to.path.startsWith('/main')) {
      ElMessage.warning('当前账号未登陆，请先登陆后在操作')
      next('/login')
    } else {
      next()
    }
  }

  // if (to.path === '/main' && !token) {
  //   ElMessage.info('当前账号未登陆，请先登陆后在操作')
  //   next('/login')
  // } else {
  //   next()
  // }
})

router.afterEach(() => nprogress.done())

export default router
